package smecta.client.print.controller;

import java.awt.GraphicsEnvironment;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import javafx.fxml.FXML;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class PrintSettingsController {

    @FXML
    private TextField labelHeight, leftMargin, labelColumns, rightMargin, labelWidth;
    @FXML
    private TextField horizontal, vertical, fontSize;
    @FXML
    private Button savePaperSettingsButton, saveMarginSettingsButton, saveFontSizeButton;
    @FXML
    private Button setPrintableButton, setNonPrintableButton, savePositionButton, closeButton;
    @FXML
    private ComboBox<String> printerSelection, printModeSelection;
    @FXML
    private Button savePrinterSettingsButton, saveFontButton;
    @FXML
    private Pane draggablePane;
    @FXML
    private RadioButton Title1, Title2, Title3, Title4, Title5, Title6, Title7, Title8, Title9, Title10;
    @FXML
    private RadioButton Title11, Title12, Title13, Title14, Title15, Title16, Title17;

    private Properties properties = new Properties();
    RadioButton focusedTitle=null;
    @FXML
    public void initialize() {
        // ��ʼ���߼���������ش�ӡ��ѡ���
        printModeSelection.getItems().addAll("Font1", "Font2", "Font3");
        makeDraggable(Title1);
        makeDraggable(Title2);
        makeDraggable(Title3);
        makeDraggable(Title4);
        makeDraggable(Title5);
        makeDraggable(Title6);
        makeDraggable(Title7);
        makeDraggable(Title8);
        makeDraggable(Title9);
        makeDraggable(Title10);
        makeDraggable(Title11);
        makeDraggable(Title12);
        makeDraggable(Title13);
        makeDraggable(Title14);
        makeDraggable(Title15);
        makeDraggable(Title16);
        makeDraggable(Title17);
        loadLayout();
        loadTitleNames();
        loadPaperSettings();
        loadPrinterList();
        loadAvailableFonts();
    }
    public  void loadAvailableFonts() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = ge.getAvailableFontFamilyNames();
        printModeSelection.getItems().addAll(fontNames);
    }
    private void loadTitleNames() {
        try (BufferedReader reader = new BufferedReader(new FileReader("./dependencies/db/TitleSet.ini"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("[") && line.endsWith("]")) {
                    String id = line.substring(1, line.length() - 1).trim();
                    String titleName = null;

                    while ((line = reader.readLine()) != null && !line.startsWith("[")) {
                        if (line.startsWith("title=")) {
                            titleName = line.substring("title=".length()).trim();
                            break;
                        }
                    }

                    if (titleName != null) {
                        setRadioButtonText(id, titleName);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void loadPrinterList() {
        List<String> printerNames = Printer.getAllPrinters().stream()
                                           .map(Printer::getName)
                                           .collect(Collectors.toList());
        printerSelection.getItems().addAll(printerNames);
    }
    private void setRadioButtonText(String id, String text) {
        switch (id) {
            case "Title1":
                Title1.setText(text);
                break;
            case "Title2":
                Title2.setText(text);
                break;
            case "Title3":
                Title3.setText(text);
                break;
            case "Title4":
                Title4.setText(text);
                break;
            case "Title5":
                Title5.setText(text);
                break;
            case "Title6":
                Title6.setText(text);
                break;
            case "Title7":
                Title7.setText(text);
                break;
            case "Title8":
                Title8.setText(text);
                break;
            case "Title9":
                Title9.setText(text);
                break;
            case "Title10":
                Title10.setText(text);
                break;
            case "Title11":
                Title11.setText(text);
                break;
            case "Title12":
                Title12.setText(text);
                break;
            case "Title13":
                Title13.setText(text);
                break;
            case "Title14":
                Title14.setText(text);
                break;
            case "Title15":
                Title15.setText(text);
                break;
            case "Title16":
                Title16.setText(text);
                break;
            case "Title17":
                Title17.setText(text);
                break;
        }
    }

    private void makeDraggable(RadioButton Title) {
        final Delta dragDelta = new Delta();

        Title.setOnMousePressed(mouseEvent -> {
            dragDelta.x = Title.getLayoutX() - mouseEvent.getSceneX();
            dragDelta.y = Title.getLayoutY() - mouseEvent.getSceneY();
            Title.setCursor(javafx.scene.Cursor.MOVE);
            focusedTitle=Title;
        });

        Title.setOnMouseReleased(mouseEvent -> {
            Title.setCursor(javafx.scene.Cursor.HAND);
            setHVText(Title);
        });

        Title.setOnMouseDragged(mouseEvent -> {
            Title.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
            Title.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
            setHVText(Title);
        });

        Title.setOnMouseEntered(mouseEvent -> {
            if (!mouseEvent.isPrimaryButtonDown()) {
                Title.setCursor(javafx.scene.Cursor.HAND);
            }
        });

        Title.setOnMouseExited(mouseEvent -> {
            if (!mouseEvent.isPrimaryButtonDown()) {
                Title.setCursor(javafx.scene.Cursor.DEFAULT);
            }
        });
    }

    public void setHVText(RadioButton Title) {
        horizontal.setText("" + Title.getLayoutX());
        vertical.setText("" + Title.getLayoutY());
    }

    public void saveLayout() {
        properties.setProperty("Title1.x", String.valueOf(Title1.getLayoutX()));
        properties.setProperty("Title1.y", String.valueOf(Title1.getLayoutY()));
        properties.setProperty("Title2.x", String.valueOf(Title2.getLayoutX()));
        properties.setProperty("Title2.y", String.valueOf(Title2.getLayoutY()));
        properties.setProperty("Title3.x", String.valueOf(Title3.getLayoutX()));
        properties.setProperty("Title3.y", String.valueOf(Title3.getLayoutY()));
        properties.setProperty("Title4.x", String.valueOf(Title4.getLayoutX()));
        properties.setProperty("Title4.y", String.valueOf(Title4.getLayoutY()));
        properties.setProperty("Title5.x", String.valueOf(Title5.getLayoutX()));
        properties.setProperty("Title5.y", String.valueOf(Title5.getLayoutY()));
        properties.setProperty("Title6.x", String.valueOf(Title6.getLayoutX()));
        properties.setProperty("Title6.y", String.valueOf(Title6.getLayoutY()));
        properties.setProperty("Title7.x", String.valueOf(Title7.getLayoutX()));
        properties.setProperty("Title7.y", String.valueOf(Title7.getLayoutY()));
        properties.setProperty("Title8.x", String.valueOf(Title8.getLayoutX()));
        properties.setProperty("Title8.y", String.valueOf(Title8.getLayoutY()));
        properties.setProperty("Title9.x", String.valueOf(Title9.getLayoutX()));
        properties.setProperty("Title9.y", String.valueOf(Title9.getLayoutY()));
        properties.setProperty("Title10.x", String.valueOf(Title10.getLayoutX()));
        properties.setProperty("Title10.y", String.valueOf(Title10.getLayoutY()));
        properties.setProperty("Title11.x", String.valueOf(Title11.getLayoutX()));
        properties.setProperty("Title11.y", String.valueOf(Title11.getLayoutY()));
        properties.setProperty("Title12.x", String.valueOf(Title12.getLayoutX()));
        properties.setProperty("Title12.y", String.valueOf(Title12.getLayoutY()));
        properties.setProperty("Title13.x", String.valueOf(Title13.getLayoutX()));
        properties.setProperty("Title13.y", String.valueOf(Title13.getLayoutY()));
        properties.setProperty("Title14.x", String.valueOf(Title14.getLayoutX()));
        properties.setProperty("Title14.y", String.valueOf(Title14.getLayoutY()));
        properties.setProperty("Title15.x", String.valueOf(Title15.getLayoutX()));
        properties.setProperty("Title15.y", String.valueOf(Title15.getLayoutY()));
        properties.setProperty("Title16.x", String.valueOf(Title16.getLayoutX()));
        properties.setProperty("Title16.y", String.valueOf(Title16.getLayoutY()));
        properties.setProperty("Title17.x", String.valueOf(Title17.getLayoutX()));
        properties.setProperty("Title17.y", String.valueOf(Title17.getLayoutY()));

        try (OutputStream output = new FileOutputStream("./samplePanel.ini")) {
            properties.store(output, null);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }

    public void loadLayout() {
        try (InputStream input = new FileInputStream("./samplePanel.ini")) {
            properties.load(input);

            Title1.setLayoutX(Double.parseDouble(properties.getProperty("Title1.x", "50")));
            Title1.setLayoutY(Double.parseDouble(properties.getProperty("Title1.y", "30")));
            Title2.setLayoutX(Double.parseDouble(properties.getProperty("Title2.x", "50")));
            Title2.setLayoutY(Double.parseDouble(properties.getProperty("Title2.y", "60")));
            Title3.setLayoutX(Double.parseDouble(properties.getProperty("Title3.x", "50")));
            Title3.setLayoutY(Double.parseDouble(properties.getProperty("Title3.y", "90")));
            Title4.setLayoutX(Double.parseDouble(properties.getProperty("Title4.x", "50")));
            Title4.setLayoutY(Double.parseDouble(properties.getProperty("Title4.y", "120")));
            Title5.setLayoutX(Double.parseDouble(properties.getProperty("Title5.x", "50")));
            Title5.setLayoutY(Double.parseDouble(properties.getProperty("Title5.y", "150")));
            Title6.setLayoutX(Double.parseDouble(properties.getProperty("Title6.x", "50")));
            Title6.setLayoutY(Double.parseDouble(properties.getProperty("Title6.y", "180")));
            Title7.setLayoutX(Double.parseDouble(properties.getProperty("Title7.x", "50")));
            Title7.setLayoutY(Double.parseDouble(properties.getProperty("Title7.y", "210")));
            Title8.setLayoutX(Double.parseDouble(properties.getProperty("Title8.x", "50")));
            Title8.setLayoutY(Double.parseDouble(properties.getProperty("Title8.y", "240")));
            Title9.setLayoutX(Double.parseDouble(properties.getProperty("Title9.x", "50")));
            Title9.setLayoutY(Double.parseDouble(properties.getProperty("Title9.y", "270")));
            Title10.setLayoutX(Double.parseDouble(properties.getProperty("Title10.x", "50")));
            Title10.setLayoutY(Double.parseDouble(properties.getProperty("Title10.y", "300")));
            Title11.setLayoutX(Double.parseDouble(properties.getProperty("Title11.x", "50")));
            Title11.setLayoutY(Double.parseDouble(properties.getProperty("Title11.y", "330")));
            Title12.setLayoutX(Double.parseDouble(properties.getProperty("Title12.x", "50")));
            Title12.setLayoutY(Double.parseDouble(properties.getProperty("Title12.y", "360")));
            Title13.setLayoutX(Double.parseDouble(properties.getProperty("Title13.x", "50")));
            Title13.setLayoutY(Double.parseDouble(properties.getProperty("Title13.y", "390")));
            Title14.setLayoutX(Double.parseDouble(properties.getProperty("Title14.x", "50")));
            Title14.setLayoutY(Double.parseDouble(properties.getProperty("Title14.y", "420")));
            Title15.setLayoutX(Double.parseDouble(properties.getProperty("Title15.x", "50")));
            Title15.setLayoutY(Double.parseDouble(properties.getProperty("Title15.y", "450")));
            Title16.setLayoutX(Double.parseDouble(properties.getProperty("Title16.x", "50")));
            Title16.setLayoutY(Double.parseDouble(properties.getProperty("Title16.y", "480")));
            Title17.setLayoutX(Double.parseDouble(properties.getProperty("Title17.x", "50")));
            Title17.setLayoutY(Double.parseDouble(properties.getProperty("Title17.y", "510")));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void savePaperSettings() {
        properties.setProperty("labelHeight", labelHeight.getText());
        properties.setProperty("leftMargin", leftMargin.getText());
        properties.setProperty("labelColumns", labelColumns.getText());
        properties.setProperty("rightMargin", rightMargin.getText());
        properties.setProperty("labelWidth", labelWidth.getText());
        properties.setProperty("printerSelection", printerSelection.getSelectionModel().getSelectedItem());
        properties.setProperty("printModeSelection", printModeSelection.getSelectionModel().getSelectedItem());
        try (OutputStream output = new FileOutputStream("./samplePanel.ini")) {
            properties.store(output, null);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }

    public void loadPaperSettings() {
        try (InputStream input = new FileInputStream("./samplePanel.ini")) {
            properties.load(input);

            labelHeight.setText(properties.getProperty("labelHeight", "0"));
            leftMargin.setText(properties.getProperty("leftMargin", "0"));
            labelColumns.setText(properties.getProperty("labelColumns", "0"));
            rightMargin.setText(properties.getProperty("rightMargin", "0"));
            labelWidth.setText(properties.getProperty("labelWidth", "0"));
            fontSize.setText(properties.getProperty("fontSize", "0"));
            printerSelection.getSelectionModel().select(properties.getProperty("printerSelection", ""));
            printModeSelection.getSelectionModel().select(properties.getProperty("printModeSelection", ""));
            updateRadioButtonColor(Title1);
            updateRadioButtonColor(Title2);
            updateRadioButtonColor(Title3);
            updateRadioButtonColor(Title4);
            updateRadioButtonColor(Title5);
            updateRadioButtonColor(Title6);
            updateRadioButtonColor(Title7);
            updateRadioButtonColor(Title8);
            updateRadioButtonColor(Title9);
            updateRadioButtonColor(Title10);
            updateRadioButtonColor(Title11);
            updateRadioButtonColor(Title12);
            updateRadioButtonColor(Title13);
            updateRadioButtonColor(Title14);
            updateRadioButtonColor(Title15);
            updateRadioButtonColor(Title16);
            updateRadioButtonColor(Title17);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    private void updateRadioButtonColor(RadioButton radioButton) {
        String printable = properties.getProperty(radioButton.getId() + ".printable", "false");
        if ("true".equals(printable)) {
            radioButton.setStyle("-fx-background-color: green;");
        } else {
            radioButton.setStyle("-fx-background-color: red;");
        }
    }

    @FXML
    private void handlePrint() {
        PrinterJob job = PrinterJob.createPrinterJob();
        if (job != null && job.showPrintDialog(this.draggablePane.getScene().getWindow())) {
            boolean success = job.printPage(this.draggablePane);
            if (success) {
                job.endJob();
            }
        }
    }

    private class Delta {
        double x, y;
    }

    @FXML
    private void handleSavePaperSettings() {
        savePaperSettings();
        System.out.println("handleSavePaperSettings");
    }

    @FXML
    private void handleSaveMarginSettings() {
        savePaperSettings();
        System.out.println("handleSaveMarginSettings");
    }

    @FXML
    private void handleSaveFontSize() {
        System.out.println("focusedTitle:"+focusedTitle);
        if (focusedTitle != null) {
            properties.setProperty(focusedTitle.getId() +  ".fontSize", fontSize.getText());
            saveProperties();
            System.out.println("���������С"+focusedTitle.getId());
        }
       
    }

    @FXML
    private void handleSetPrintable() {
        System.out.println("focusedTitle:"+focusedTitle);
        if (focusedTitle != null) {
            properties.setProperty(focusedTitle.getId() + ".printable", "true");
            saveProperties();
            focusedTitle.setStyle("-fx-background-color: green;");
        }
        System.out.println("���ÿɴ�");
    }

    @FXML
    private void handleSetNonPrintable() {
    	  System.out.println("focusedTitle:"+focusedTitle);
        if (focusedTitle != null) {
            properties.setProperty(focusedTitle.getId() + ".printable", "false");
            saveProperties();
            focusedTitle.setStyle("-fx-background-color: red;");
        }
        System.out.println("���ò���");
    }

    @FXML
    private void handleSavePosition() {
        saveLayout();
        System.out.println("����λ��");
    }

    @FXML
    private void handleClose() {
        // �رմ���
        Stage stage = (Stage) closeButton.getScene().getWindow();
        stage.close();
    }

    @FXML
    private void handleSaveSettings() {
    	saveLayout();
    	savePaperSettings();
        System.out.println("�����ӡ������");
    }

    @FXML
    private void handleSaveFont() {
    	savePaperSettings();
        System.out.println("������������");
    }

    private RadioButton getSelectedRadioButton() {
        return focusedTitle;
    }
    private void saveProperties() {
        try (OutputStream output = new FileOutputStream("./samplePanel.ini")) {
            properties.store(output, null);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }
}
